import { configureStore, combineReducers } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from "redux-persist";
import {
	TypedUseSelectorHook,
	useDispatch as useReduxDispatch,
	useSelector as useReduxSelector
} from "react-redux";
import storage from "redux-persist/lib/storage";
import reduxThunk from "redux-thunk";
import reduxPromise from "redux-promise";

import global from "./modules/global";

const reducer = combineReducers({
	global
});

const persistConfig = {
	key: "redux-state",
	storage: storage
	// blacklist: ["global"] // 不需要持久化存储的reducer
};

const persistReducerConfig = persistReducer(persistConfig, reducer);

// store
export const store = configureStore({
	reducer: persistReducerConfig,
	middleware: getDefaultMiddleware =>
		getDefaultMiddleware({
			reduxThunk,
			reduxPromise,
			serializableCheck: false
		}),
	devTools: true
});

// create persist store
export const persistor = persistStore(store);

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export const useSelector: TypedUseSelectorHook<RootState> = useReduxSelector;
export const useDispatch = () => useReduxDispatch<AppDispatch>();
